﻿using ERP.ERPSystem.WarehouseManagement.Dto;
using ERP.Team.ProductionSystem;
using ERP.Team.WarehouseManagement;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace ERP.ERPSystem.WarehouseManagement
{
    /// <summary>
    /// 仓储管理-赋码管理服务类
    /// </summary>
    public class CodingManagementService : ApplicationService, ICodingManagementService
    {
        private readonly IRepository<CodingManagementModel, int> _repository;
        private readonly IRepository<MaterialproductModel, int> _materialProductRepository;

        public CodingManagementService(
            IRepository<CodingManagementModel, int> repository,
            IRepository<MaterialproductModel, int> materialProductRepository)
        {
            _repository = repository;
            _materialProductRepository = materialProductRepository;
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        public async Task<(List<CodingManagementDTO> Items, int TotalCount)> GetPagedListAsync(
            string codeType, string businessCode, string businessName, int skipCount, int maxResultCount)
        {
            // 构建查询条件
            var query = await _repository.GetQueryableAsync();
            
            if (!string.IsNullOrWhiteSpace(codeType))
            {
                query = query.Where(x => x.BarTypes == codeType);
            }
            
            if (!string.IsNullOrWhiteSpace(businessCode))
            {
                query = query.Where(x => x.BusinessCode.Contains(businessCode));
            }
            
            if (!string.IsNullOrWhiteSpace(businessName))
            {
                query = query.Where(x => x.BusinessName.Contains(businessName));
            }

            // 获取总数
            var totalCount = await AsyncExecuter.CountAsync(query);

            // 获取分页数据
            var items = await AsyncExecuter.ToListAsync(
                query.Skip(skipCount)
                    .Take(maxResultCount)
            );

            return (ObjectMapper.Map<List<CodingManagementModel>, List<CodingManagementDTO>>(items), totalCount);
        }

        /// <summary>
        /// 新增编码
        /// </summary>
        public async Task<CodingManagementDTO> CreateAsync(CodingManagementDTO input)
        {
            try
            {
                var entity = ObjectMapper.Map<CodingManagementDTO, CodingManagementModel>(input);
                
                // 设置条码图片URL，使用input.url而不是生成新的URL
                if (!string.IsNullOrEmpty(input.Url))
                {
                    entity.Url = input.Url;
                }
                
                var result = await _repository.InsertAsync(entity);
                return ObjectMapper.Map<CodingManagementModel, CodingManagementDTO>(result);
            }
            catch (Exception ex)
            {
                Logger.LogError($"创建编码失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 生成条码
        /// </summary>
        public async Task<string> GenerateBarcodeAsync(string barFormat)
        {
            // 生成时间戳
            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            // 生成6位随机数
            var random = new Random();
            var randomNumber = random.Next(100000, 999999);
            
            // 根据不同的条码格式生成不同的前缀
            string prefix = barFormat switch
            {
                "QR二维码" => "QR",
                "EAN码" => "EAN",
                "UPC码" => "UPC",
                _ => "STD"
            };

            // 组合条码：前缀 + 时间戳 + 随机数
            var barcode = $"{prefix}{timestamp}{randomNumber}";
            
            return await Task.FromResult(barcode);
        }

        /// <summary>
        /// 获取物料产品分页列表
        /// </summary>
        public async Task<(List<CodingMaterialProductDTO> Items, int TotalCount)> GetMaterialProductPagedListAsync(
            string materialCode,
            string materialName,
            int skipCount,
            int maxResultCount)
        {
            try
            {
                var query = await _materialProductRepository.GetQueryableAsync();

                // 只查询启用的记录
                query = query.Where(x => x.IsNo == 1);

                if (!string.IsNullOrWhiteSpace(materialCode))
                {
                    query = query.Where(x => x.MaterielCode.Contains(materialCode));
                }

                if (!string.IsNullOrWhiteSpace(materialName))
                {
                    query = query.Where(x => x.MaterielName.Contains(materialName));
                }

                var totalCount = await AsyncExecuter.CountAsync(query);

                var items = await AsyncExecuter.ToListAsync(
                    query.OrderByDescending(x => x.CreateTime)
                        .Skip(skipCount)
                        .Take(maxResultCount)
                );

                var dtos = ObjectMapper.Map<List<MaterialproductModel>, List<CodingMaterialProductDTO>>(items);

                return (dtos, totalCount);
            }
            catch (Exception ex)
            {
                Logger.LogError($"获取物料产品列表失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 删除编码
        /// </summary>
        public async Task DeleteAsync(int id)
        {
            try
            {
                await _repository.DeleteAsync(id);
            }
            catch (Exception ex)
            {
                Logger.LogError($"删除编码失败: {ex.Message}");
                throw;
            }
        }
    }
}
